package ac.il.technion.cs236369.hw5.core.reports;

import java.io.IOException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

/**
 * Servlet implementation class ReportGenerator
 */
public class ReportGenerator extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReportGenerator() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost( request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = null;
		String idKey = "projectId";
		String operation = "project_summary";
		id = request.getParameter( "projectId");
		if ( id == null) {
			id = request.getParameter( "userId");
			operation = "user_summary";
			idKey = "userId";
		}
		if ( id == null) {
			id = request.getParameter( "instrumentId");
			operation = "instrument_summary";
			idKey = "instrumentId";
		}
		String host = "http://" + request.getServerName( ) + ":" + request.getServerPort( );
		URL xmlUrl = new URL( host+ "/FinalProject/app/reportManagement?reportOp=" + operation + "&" + idKey + "=" + id);
		URL xslUrl = new URL( host+ "/FinalProject/app/xsltStorageManagement?xsltStorageOp=xslt_get_content&id=" + request.getParameter( "xsltId"));
		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer;
		try {
			transformer = tFactory.newTransformer(new StreamSource(xslUrl.openStream( )));
			transformer.transform(new StreamSource(xmlUrl.openStream( )), new StreamResult(response.getWriter( )));
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}

}
